﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.Data.Objects;
using Statistics.BLL;
using System.Data;
using System.Globalization;
using System.Threading;

namespace TestSuiteExtNET
{
    public partial class Demo2_3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                GetUsersCount();

                PrepareChart2();

                LoadSiteNames();

                //Statistics.StatisticsController cntr = new Statistics.StatisticsController();
                //Store s = this.grdData.GetStore();
                //s.DataSource = cntr.GetGridData();
                //s.DataBind();
            }
        }

        protected void ReloadData(object sender, DirectEventArgs e)
        {
            string s = null;
            if (this.mcSites.SelectedItems.Count() > 0)
            {
                foreach (Ext.Net.ListItem o in this.mcSites.SelectedItems)
                {
                    s += string.Format("{0},", o.Text);
                }
                s = s.Substring(0, s.Length - 1);
            }
            //DateTime? dtFrom = (this.dtFrom.Value == null ? null : (DateTime?)this.dtFrom.Value);
            //DateTime? dtTo = (this.dtTo.Value == null ? null : (DateTime?)((DateTime)this.dtTo.Value).AddHours(23).AddMinutes(59).AddSeconds(59));

            DateTime? dtFrom;
            DateTime? dtTo;
            if ((this.dtFrom.Value == null) || (((DateTime)this.dtFrom.Value).Equals(DateTime.MinValue)))
            {
                dtFrom = null;
            }
            else
            {
                dtFrom = (DateTime)this.dtFrom.Value;
            }

            if ((this.dtTo.Value == null) || (((DateTime)this.dtTo.Value).Equals(DateTime.MinValue)))
            {
                dtTo = null;
            }
            else
            {
                dtTo = (DateTime)this.dtTo.Value;
            }
            
            DataTable dt = GenerateDynamicData3(dtFrom, dtTo, s);

            CreateChart(dt);

            this.Chart1.Render();

            this.gaugesPanel.Items.Clear();
            GetUsersCount();
            this.gaugesPanel.Render();
        }

        private void LoadSiteNames()
        {
            Statistics.StatisticsController cntr = new Statistics.StatisticsController();

            Store store = this.mcSites.GetStore();
            store.DataSource = cntr.GetSiteNames();
            store.DataBind();
        }

        private void PrepareChart2()
        {
            DataTable dt = GenerateDynamicData3(null, null, null);

            CreateChart(dt);
        }

        private DataTable GenerateDynamicData3(DateTime? from, DateTime? to, string sites)
        {
            Statistics.StatisticsController cntr = new Statistics.StatisticsController();
            DataTable retValue = cntr.GetUsersInPeriod2(from, to, sites);
            return retValue;
        }

        private void GetUsersCount()
        {
            List<Statistics.BLL.UsersStats> data = GetData();

            this.gaugesPanel.Height = 150 * data.Count();

            int totale = data.Sum(x => x.UserCounts);

            string s = string.Empty;
            foreach (Ext.Net.ListItem o in this.mcSites.SelectedItems)
            {
                s += string.Format("{0},", o.Text);
            }

            if (!string.IsNullOrWhiteSpace(s))
            {
                for (int i = data.Count - 1; i >= 0; i--)
                {
                    if (!s.Contains(data[i].SiteName))
                    {
                        data.RemoveAt(i);
                    }
                }
            }

            int h = 0;
            foreach (Statistics.BLL.UsersStats obj in data)
            {
                Chart gauge = CreateGauge(obj.SiteName, totale, data.FindAll(x => x.SiteName == obj.SiteName));

                h += 150;

                this.gaugesPanel.Items.Add(gauge);
            }

            this.gaugesPanel.Height = new Unit(h);
            this.gaugesPanel.Border = false;
        }

        private List<Statistics.BLL.UsersStats> GetData()
        {
            Statistics.StatisticsController cntr = new Statistics.StatisticsController();
            List<Statistics.BLL.UsersStats> retValue = cntr.GetUsersSubscriptionCount();

            return retValue;
        }

        private Chart CreateGauge(string name, int total, List<Statistics.BLL.UsersStats> data)
        {
            Chart retValue = null;

            GaugeSeries gs = new GaugeSeries();
            gs.AngleField = "UserCounts";
            gs.Donut = 50;
            gs.ColorSet = new string[] { "#82B525", "#ddd" };
            gs.Title = name;
            gs.Highlight = true;

            GaugeAxis ga = new GaugeAxis();
            ga.Minimum = 0;
            ga.Maximum = total;
            ga.Steps = 5;
            ga.Margin = 5;
            ga.Title = name;

            retValue = new Chart();
            retValue.Animate = true;
            retValue.StyleSpec = "background:#fff;";
            //retValue.InsetPadding = 20;
            //retValue.AutoSize = true;
            //retValue.ViewBox = false;
            retValue.Height = new Unit(50);
            retValue.Flex = 3;
            retValue.Resizable = false;
            retValue.ID = string.Format("gauge{0}", name);
            retValue.ClientIDMode = System.Web.UI.ClientIDMode.Static;
            retValue.Axes.Add(ga);
            retValue.Series.Add(gs);

            if (data != null)
            {
                Model.Config modelCfg = new Model.Config();
                modelCfg.Fields.Add(new ModelField("SiteName"));
                modelCfg.Fields.Add(new ModelField("UserCounts"));

                Model m_model = new Model();
                m_model.ID = string.Format("model{0}", name);
                m_model.ClientIDMode = System.Web.UI.ClientIDMode.Static;

                m_model.Fields.Add(new ModelField("SiteName", ModelFieldType.String));
                m_model.Fields.Add(new ModelField("UserCounts", ModelFieldType.Int));

                Store.Config storeCfg = new Store.Config();
                storeCfg.AutoDataBind = true;
                storeCfg.Model.Add(m_model);

                
                Store m_store = new Store();
                m_store.ID = string.Format("store{0}", name);
                m_store.ClientIDMode = System.Web.UI.ClientIDMode.Static;
                m_store.Model.Add(m_model);
                m_store.DataSource = data;
                m_store.DataBind();

                ModelProxy mp = new ModelProxy(m_store);
                
                retValue.Store.Add(m_store);
            }

            return retValue;
        }

        private void CreateChart(DataTable data)
        {
            if (data.Rows.Count == 0)
            {
                //this.Chart1.Visible = false;


                //this.drwText.Visible = true;
                //this.drwText.Render();
            }
            else
            {
                //this.Chart1.Visible = true;
     

                //this.drwText.Visible = false;
                //this.drwText.Render();

                List<string> listColumns = new List<string>();
                List<LineSeries> listLineSeries = new List<LineSeries>();

                string[] xFieldName = new string[] { data.Columns[0].ColumnName };

                // creo le serie...
                foreach (DataColumn c in data.Columns)
                {
                    if (c.Ordinal == 0) continue;

                    LineSeries line = new LineSeries()
                    {
                        Title = c.ColumnName,
                        XField = xFieldName,
                        YField = new string[] { c.ColumnName },
                        Highlight = true
                    };

                    listColumns.Add(c.ColumnName);
                    listLineSeries.Add(line);
                }

                // crea gli assi...
                TimeAxis ca = new TimeAxis();
                ca.Fields = xFieldName;
                ca.Position = Position.Bottom;
                ca.DateFormat = "MMM dd";
                ca.Constrain = true;
                ca.Title = "Periodo";
                ca.Label = new AxisLabel() { Font = "9px Arial", Rotate = new RotateAttribute() { Degrees = 270 } };
                //ca.Label.Rotate = new RotateAttribute() { Degrees=270 };

                NumericAxis na = new NumericAxis();
                na.Fields = listColumns.ToArray();
                na.Position = Position.Left;
                na.MinorTickSteps = 1;
                na.MajorTickSteps = 1;
                na.Minimum = 0;

                this.Chart1.Axes.Add(na);
                this.Chart1.Axes.Add(ca);
                listLineSeries.ForEach(x => { this.Chart1.Series.Add(x); });

                // creo lo store...
                Store store = new Store();
                var model = new Model();
                model.Fields.Add(new ModelField(xFieldName[0], ModelFieldType.String));

                listColumns.ForEach(column =>
                {
                    model.Fields.Add(new ModelField(column, ModelFieldType.Int));
                });

                store.Model.Add(model);

                //Carrega o store
                store.DataSource = data;

                //Adiciona o stre ao gráfico
                this.Chart1.Store.Add(store);
            }
        }
    }
}
